package com.cqgcxy.shopping.common;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;




/**
 * 过滤未登录和未注册的用户
 * @author 方昆
 *
 */
@WebFilter(urlPatterns="/*")
public class LoginFilter implements Filter{
	private Logger logger=LoggerFactory.getLogger(getClass());
	//静态资源、登录页面、错误页面、注册页面都不做登录检查,直接往后请求
	private String[] unLogins=new String[]{"register","login","assets","error","kaptcha.png"};
	/**
	 * 检查url中是否包含指定的字符串
	 * @param url
	 * @return
	 */
	private boolean contains(String url) {
		for(int i=0;i<unLogins.length;i++) {
			if(url.contains(unLogins[i])) {
				return true;
			}
		}
		return false;
	}
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request=(HttpServletRequest)req;
		HttpServletResponse response=(HttpServletResponse)resp;
		HttpSession session=request.getSession();
		Object ouser=session.getAttribute("user");
		String url=request.getRequestURI();
		//检查是否有用户登录
		if(ouser!=null) {
			logger.debug("已经登录:{}",url);
			chain.doFilter(request, response); //直接执行后面的请求
		}else {
			logger.debug("没有登录:{}",url);
			if(contains(url)) { //没有登录时:静态资源、登录页面、错误页面、注册页面都不做登录检查
				chain.doFilter(request, response); //直接执行请求
			}else {
				response.sendRedirect(request.getContextPath()+"/login.jsp");
			}
		}
	}
	
	@Override
	public void destroy() {
	}

}
